<template>
  <div>
    <!-- right-list-box start -->
    <div
        class="right-list-box"
        :class="{ 'unlock-list-active': !isListLocked }"
    >
      <div class="top">
        <div>
          <el-checkbox
              v-model="allChecked"
              v-show="isCanEdit"
              @change="changeAllCheck"
              :disabled="isListLocked"
              :indeterminate="isIndeterminate"
          >全选
          </el-checkbox
          >
          <i
              @click="changeListLocked"
              :class="[isListLocked ? 'icon-locked' : 'icon-lock']"
              v-show="isCanEdit"
          ></i>
        </div>
        <div class="menu">
          <div class="border-box">
            <span
                title="大图视图"
                :class="{ active: isMulti }"
                @click="changeMulit(true)"
            >
              <i :class="[isMulti ? 'icon-multi' : 'icon-multi1']"></i>
            </span>
            <span
                title="列表视图"
                :class="{ active: !isMulti }"
                @click="changeMulit(false)"
            >
              <i :class="[!isMulti ? 'icon-list' : 'icon-list1']"></i>
            </span>
          </div>
          <i class="icon-add" v-show="isCanEdit" @click="openPanel('add')" title="新增视点"></i>
          <i class="icon-delete1" title="删除" @click="deleteList"></i>
        </div>
      </div>

      <div class="btm ag-scrollbar">
        <!-- 大图 picture-item start -->
        <template v-if="isMulti">
          <div
              class="picture-item"
              v-for="(record, index) in nowViewList"
              :key="record.imageStoreId"
              :class="{ select: isSelect === index }"
              :draggable="!isListLocked"
              @dragstart="dragstart(record)"
              @dragenter="dragenter(record)"
              @dragend="dragend(record)"
          >
            <el-checkbox
                v-model="record.checked"
                @change="changeCheck"
                v-show="isCanEdit"
            ></el-checkbox>
            <img :src="record.imageStoreCode" @click="flyCameraByClickTableRow(record, index)" :class="!isListLocked ? 'itemUnLocked': ''"/>
            <i v-if="record.initialSpot" class="initial"></i>
            <el-tooltip
                v-if="record.imageStoreName.length > 10"
                :content="record.imageStoreName"
                placement="bottom-start"
                effect="dark"
            >
              <p class="name">{{ record.imageStoreName }}</p>
            </el-tooltip>
            <p class="name" v-else>{{ record.imageStoreName }}</p>
            <el-tooltip v-show="isCanEdit">
              <template slot="content"> 编辑</template>
              <span class="ibox edit">
                <i
                    class="agcim-edit_outlined iconfont icon"
                    @click.stop="openPanel('edit', record)"
                ></i>
              </span>
            </el-tooltip>
            <el-tooltip v-show="isCanEdit">
              <template slot="content"> 删除</template>
              <span class="ibox delete">
                <el-popconfirm
                    title="是否确认要删除这个视点？"
                    @confirm="deleteCertain(record)"
                    confirm-button-text="确认"
                    cancel-button-text="取消"
                >
                  <i slot="reference" class="agcim-trash iconfont icon"></i>
                </el-popconfirm>
              </span>
            </el-tooltip>
          </div>
        </template>
        <!-- 大图 picture-item end -->
        <!-- 缩略图 thumb-item start -->
        <template v-if="!isMulti">
          <div
              class="thumb-div"
              v-for="(record, index) in nowViewList"
              :key="record.imageStoreId"
              :class="{ select: isSelect === index }"
              :draggable="!isListLocked"
              @dragstart="dragstart(record)"
              @dragenter="dragenter(record)"
              @dragend="dragend(record)"
          >
            <el-checkbox
                class="thumb-checkbox"
                v-model="record.checked"
                @change="changeCheck"
            ></el-checkbox>
            <div class="thumb-item"
                 @click="flyCameraByClickTableRow(record, index)"
            >
              <div>
                <span class="record-index">{{ index + 1 }}</span>
                <img :src="record.imageStoreCode"/>
                <el-tooltip
                    v-if="record.imageStoreName.length > 10"
                    :content="record.imageStoreName"
                    placement="bottom-start"
                    effect="dark"
                >
                  <span class="record-name">{{ record.imageStoreName }}</span>
                </el-tooltip>
                <span class="record-name" v-else>{{
                    record.imageStoreName
                  }}</span>
              </div>
              <div class="rt" v-show="isCanEdit">
              <span
              ><i
                  class="icon-edit"
                  @click.stop="openPanel('edit', record)"
              ></i
              ></span>
                <el-tooltip>
                  <template slot="content"> 删除</template>
                  <span class="ibox delete">
                  <el-popconfirm
                      title="是否确认要删除这个视点？"
                      @confirm="deleteCertain(record)"
                      confirm-button-text="确认"
                      cancel-button-text="取消"
                  >
                    <i slot="reference" class="icon-delete"></i>
                  </el-popconfirm>
                </span>
                </el-tooltip>
              </div>
            </div>
          </div>
        </template>
        <!-- 缩略图 thumb-item end -->
      </div>
      <!--增加底部复选框-->
      <div class="view-layer-selector">
        <el-checkbox-group v-model="checkedList" @change="selectorChange">
          <el-checkbox
              v-for="(item, index) in plainOptions"
              :label="item"
              :key="item"
              @change="
              (item) => {
                selectorItemChange(plainOptions[index]);
              }
            "
          >
            {{ item }}
          </el-checkbox
          >
        </el-checkbox-group>
      </div>
    </div>
    <AddOrEditViewPoint
        :visible="visible_addViewPoint"
        :list="list"
        :addViewPointPopup="viewPointPopup"
        :nowSelectGroupId="nowSelectGroupId"
        :nowViewPoint="nowViewPoint"
        @updateList="updateList"
        @close="visible_addViewPoint = false"
        :getOtherGroup="getOtherGroup"
    ></AddOrEditViewPoint>
    <!-- right-list-box end -->
  </div>
</template>
<script>
import imageDataApi from "@/views/js/api/imageDataApi";
import AddOrEditViewPoint from "./addOrEditViewPoint.vue";
import ScenePlan from "../js/scenePlan";
import configData from "../data/index";

let scenePlan;
export default {
  props: {
    list: {
      type: Array,
      default: () => [],
    },
    nowSelectGroupId: {
      type: String,
      default: "全部",
    },
    isCanEdit: {
      type: Boolean,
      default: false,
    },
    getOtherGroup: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    list(nv) {
      this.nowViewList = nv;
    },
  },
  components: {
    AddOrEditViewPoint,
  },
  mounted() {
  },
  data() {
    return {
      checkedList: ["视点位置", "视点图层"], //复选框选中的数据
      plainOptions: [
        "视点位置",
        "视点图层",
        "禁用动画",
        // "场景方案",
        // "地形压平",
      ], //复选框的所有选项
      visible_addViewPoint: false, //是否打开弹框
      viewPointPopup: "add", //打开弹框的类型 add/edit
      nowViewPoint: null, //当前编辑的行
      //全选
      allChecked: false,
      isSelect: -1,
      //是否列表
      isMulti: true,
      //列表是否锁上
      isListLocked: true,
      //半选中
      isIndeterminate: false,
      //选中的数组
      viewCheckedList: [],
      //当前的列表
      nowViewList: [],
    };
  },
  methods: {
    resetAllChecked(){
      this.allChecked = false;
      this.isIndeterminate = false;
    },
    updateList(){
      this.$emit('getNewList', this.nowSelectGroupId);
      this.allChecked = false;
      this.isIndeterminate = false;
      this.nowViewList.forEach((item) => {
        item.checked = false;
      })
    },
    /**
     * @lastUpdateBy : 韩怡婷
     * @description: 删除选中的多个视点
     */
    deleteList() {
      let vm = this;
      this.$confirm("你确定要删除选中的视点吗？", "视点删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning",
        center: true,
      })
          .then(async () => {
            let arr = this.viewCheckedList;
            for (let j = 0; j < arr.length; j++) {
              let formData = new FormData();
              formData.append("paramId", arr[j].imageStoreId);
              let data = await imageDataApi.deleteImageStore(formData);
              if (data.success) {
                if (j == arr.length - 1) {
                  vm.$emit("getNewList", vm.nowSelectGroupId);
                  vm.allChecked = false;
                  vm.isIndeterminate = false;
                  vm.$message.success("删除成功");
                }
              } else {
                vm.$message.error(data.message);
              }
            }
          })
          .catch(() => {
            // vm.$message.success('取消');
          });
    },
    //全选
    changeAllCheck(val) {
      for (let i = 0; i < this.nowViewList.length; i++) {
        this.nowViewList[i].checked = this.allChecked;
      }
      if (val) {
        this.isIndeterminate = false;
        this.viewCheckedList = this.nowViewList;
      } else {
        this.viewCheckedList = [];
      }
    },
    changeCheck() {
      this.viewCheckedList = this.nowViewList.filter((item) => {
        return item.checked;
      });
      let len = this.viewCheckedList.length;
      if (0 < len && len < this.nowViewList.length) {
        this.allChecked = false;
        this.isIndeterminate = true;
      } else {
        if (len == this.nowViewList.length) {
          this.allChecked = true;
        } else if(len === 0){
          this.allChecked = false;
        }
        this.isIndeterminate = false;
      }
    },
    // 显示编辑视点弹窗
    openPanel(type, val) {
      this.visible_addViewPoint = true;
      this.viewPointPopup = type;
      if (type == "add") {
        this.nowViewPoint = undefined;
      } else {
        this.nowViewPoint = val;
      }
    },
    //点击列表行触发
    flyCameraByClickTableRow(r, i) {
      let _t = this;
      _t.className = r.id;
      _t.flyCamera(r, i);
      this.isSelect = i;
    },
    /**
     * @lastUpdateBy : 韩怡婷
     * @description: 点击列表定位
     * @param {*} item 单条数据
     * @param {*} index 下标
     * @return {*}
     */
    flyCamera(item, index) {
      this.isclick = index;
      let val = item.json;
      console.log(val, item);
      let isLoadLayer = this.isLoadLayer();
      //视点图层没有勾选时
      if (!isLoadLayer) {
        this.flyToTaget(val, item.jumpSpotEnable);
        return;
      }
      //自动设置时间
      if (val.time) {
        CIM.viewer.clock.currentTime = Cesium.JulianDate.fromDate(
            new Date(val.time)
        );
      }
      this.itemSelect = item; //当前选中的行
      //从创建视图时，保存的图层中读取
      this.alreadyLayer = item.json.layerId || [];
      this.addLayer(this.alreadyLayer);
      if (!item.json.functions || item.json.functions.length == 0) {
        this.undoIconShow = false;
      } else {
        this.undoIconShow = true;
      }
      if (Array.isArray(val.position)) {
        val.position = new Cesium.Cartesian3(
            val.position[0],
            val.position[1],
            val.position[2]
        );
      }
      console.log(val, item);
      this.flyToTaget(val, item.jumpSpotEnable);
      this.excuteFunction(val);
      //如果开启方案，就重置光效
      if (this.isAplayScenePlan() && scenePlan) {
        setTimeout(() => {
          scenePlan.addBuildingEffect();
        }, 1000);
      }
    },

    //拖拽
    dragstart(value) {
      if(this.isListLocked){
        return;
      }
      this.oldData = value;
    },
    dragenter(value) {
      if(this.isListLocked){
        return;
      }
      this.newData = value;
    },
    dragend(value) {
      if(this.isListLocked){
        return;
      }
      if (this.oldData !== this.newData) {
        let oldIndex = this.nowViewList.indexOf(this.oldData);
        let newIndex = this.nowViewList.indexOf(this.newData);
        let newItems = [...this.nowViewList];
        // 删除老的节点
        newItems.splice(oldIndex, 1);
        // 在列表中目标位置增加新的节点
        newItems.splice(newIndex, 0, this.oldData);
        this.nowViewList = [...newItems];
        this.dragSort(this.nowViewList);
      }
    },
    //全选
    // changeAllCheck() {
    //   for (let i = 0; i < this.nowViewList.length; i++) {
    //     this.nowViewList[i].checked = this.allChecked;
    //   }
    // },

    /**
     * @lastUpdateBy : 韩怡婷
     * @description: 删除列表视点
     * @param {*} item 单条数据
     */
    deleteCertain(item) {
      let vm = this;
      let formData = new FormData();
      formData.append("paramId", item.imageStoreId);
      let promise = imageDataApi.deleteImageStore(formData);
      promise.then(function (data) {
        if (data.success) {
          vm.$message.success("删除成功");
          vm.allChecked = false;
          vm.isIndeterminate = false;
          vm.$emit("getNewList", vm.nowSelectGroupId);
        } else {
          vm.$message.error(data.message);
        }
      });
    },
    changeMulit(isMulti) {
      this.isMulti = isMulti;
    },
    changeListLocked() {
      this.isListLocked = !this.isListLocked;
      this.isIndeterminate = false;
      this.allChecked = false;
      this.nowViewList.forEach((item) => {
        item.checked = false;
      })
    },
    /**
     * @lastUpdateBy : 韩怡婷
     * @description: 拖拽排序
     * @param {*} list 排序完的列表
     * @return {*}
     */
    dragSort(list) {
      let params = [];
      list.map((item) => {
        params.push(item.imageStoreId);
      });
      imageDataApi.dragSort(params).then((res) => {
        // if (res.success) {
        //   this.$message({
        //     message: "保存成功!",
        //     type: "success",
        //   });
        // }
      });
    },
    //执行附加功能
    excuteFunction(information, params) {
      let vm = this;
      if (!information.functions || information.functions.length == 0) return;
      information.functions.map((val) => {
        vm[val.action](val, params); //判断
      });
    },
    /*撤销图层操作 -- 附加操作反向**/
    undoLayer(item) {
      if (!item.json.functions || item.json.functions.length == 0) {
        return;
      }
      let information = {};
      information = JSON.parse(JSON.stringify(item.json));
      for (let i = 0; i < information.functions.length; i++) {
        information.functions[i].action = "closeLayer";
      }
      this.isclick = null;
      this.excuteFunction(information);
      CIM.layerTree.addMany(this.alreadyLayer, CIM.viewer);
    },
    showLayer(data) {
      let layerName = data.obj;
      let ly = CIM.layerTree.getLayerByText(layerName);
      let ids = CIM.layerTree._aglayerIds;
      //未添加，则添加
      if (ly && ly.id && ids.indexOf(ly.id) == -1) {
        CIM.layerTree.addLayer(ly, CIM.viewer);
      }
      //设置图层样式
      let tileLayer = CIM.layerTree.getLayerById(ly.id);
      if (tileLayer) {
        let tileset = tileLayer._primitives[0];
        styleCondition = new StyleCondition(tileset);
        //rgba格式的颜色转化为rgb和透明度
        let color = data.color;
        let tempval = color.replace("rgba(", "").replace(")", "").split(",");
        let param1 = `rgb(${tempval[0]},${tempval[1]},${tempval[2]})`;
        let param2 = tempval[3];
        styleCondition.resetColorStyle(param1, param2);
      }
    },
    closeLayer(data) {
      let layerName = data.obj;
      let ly = CIM.layerTree.getLayerByText(layerName);
      let ids = CIM.layerTree._aglayerIds;
      //图层样式还原
      let tileLayer = CIM.layerTree.getLayerById(ly.id);
      if (tileLayer) {
        let tileset = tileLayer._primitives[0];
        styleCondition = new StyleCondition(tileset);
        styleCondition.resetColorStyle();
        //已添加，就删除
        if (ly && ly.id && ids.indexOf(ly.id) > -1) {
          CIM.layerTree.removeLayerById(ly.id, CIM.viewer);
        }
      }
    },
    //加载图层
    addLayer(data) {
      this.removeLayer(data); //加载图层前，先清理已有的
      let currentLayer = JSON.parse(JSON.stringify(CIM.layerTree._aglayerIds));
      currentLayer = this.uniqueArr(currentLayer);
      let sameArr = this.getSameArray(data, currentLayer);
      let diffArr = this.getDiffArray(data, sameArr);
      diffArr.forEach((item) => {
        CIM.layerTree.layerTreeDom.setLayerCheck(item, true);
      });
      // this.$store.commit("setViewSelectedLayer", data); //当前图层缓存到store，同步到工具栏的“图层”
    },
    //清理图层，只是处理不同图层，相同则不处理
    removeLayer(addData) {
      let currentLayer = JSON.parse(JSON.stringify(CIM.layerTree._aglayerIds));
      currentLayer = this.uniqueArr(currentLayer);
      let sameArr = this.getSameArray(addData, currentLayer);
      let diffArr = this.getDiffArray(sameArr, currentLayer);

      diffArr.forEach((item) => {
        CIM.layerTree.layerTreeDom.setLayerCheck(item, false);
      });
    },
    //定位到视点
    flyToTaget(val, isAnimation) {
      console.log(val, isAnimation);
      let isFly = this.isFlyToTaget();
      if (!isFly) {
        return;
      }
      let notAnimation = this.isNotAnimation();
      //飞行到视点
      if (isAnimation && !notAnimation) {
        CIM.viewer.camera.flyTo({
          destination: val.position,
          orientation: {
            heading: val.heading,
            pitch: val.pitch,
            roll: val.roll,
          },
        });
      } else {
        //直接定位到视点
        CIM.viewer.camera.setView({
          destination: val.position,
          orientation: {
            heading: val.heading,
            pitch: val.pitch,
            roll: val.roll,
          },
        });
      }
    },
    //是否勾选了复选框中的视点位置，默认勾选
    isFlyToTaget() {
      return this.checkedList.includes(this.plainOptions[0]);
    },
    //是否勾选了复选框中的视点图层，默认勾选
    isLoadLayer() {
      return this.checkedList.includes(this.plainOptions[1]);
    },
    //是否勾选了禁用动画，默认不勾选
    isNotAnimation() {
      return this.checkedList.includes(this.plainOptions[2]);
    },
    //是否开启场景方案
    isAplayScenePlan() {
      return this.checkedList.includes(this.plainOptions[3]);
    },
    //是否开启地形压平
    isTerrainFlatten() {
      return this.checkedList.includes(this.plainOptions[4]);
    },
    //复选框变化事件
    selectorChange(checkedList) {
    },
    selectorItemChange(item) {
      switch (item) {
        case "地形压平":
          if (this.isTerrainFlatten()) {
            ScenePlan.flattenTerrain(
                configData.flattenRectangle,
                configData.flattenHeight
            );
          } else {
            ScenePlan.destroyedFlattenTerrain();
          }
          break;
        case "场景方案":
          if (this.isAplayScenePlan()) {
            if (!scenePlan) {
              scenePlan = new ScenePlan(CIM.viewer);
              scenePlan.init();
            }
          } else {
            if (scenePlan) {
              scenePlan.destroyed();
              scenePlan = undefined;
            }
          }
          break;
      }
    },
    //获取两个数组相同部分
    getSameArray(arrPre, arrNext) {
      let res = [];
      for (let i = 0; i < arrNext.length; i++) {
        for (let j = 0; j < arrPre.length; j++) {
          if (arrPre[j] === arrNext[i]) {
            res.push(arrPre[j]);
          }
        }
      }
      return res;
    },
    //获取两个数组不同部分
    getDiffArray(arrPre, arrNext) {
      return arrPre.concat(arrNext).filter(function (v, i, arr) {
        return arr.indexOf(v) === arr.lastIndexOf(v);
      });
    },
    //数组去重
    uniqueArr(arr) {
      return Array.from(new Set(arr));
    },
  },

  destroyed() {
    if (scenePlan) {
      scenePlan.destroyed();
      scenePlan = undefined;
    }
  },
};
</script>
<style src="../css/style.css"></style>
<style lang="less" scoped>
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;

  .menu {
    font-size: 0;
  }

  i {
    cursor: pointer;
  }

  .el-checkbox {
    color: #fff;
    margin-right: 8px;
  }
}

.border-box {
  display: inline-block;
  border: 1px solid #1e90ff;
  height: 32px;
  vertical-align: top;
  border-radius: 4px;
  margin-right: 8px;

  i {
    vertical-align: middle;
  }

  span {
    display: inline-block;
    height: 30px;
    line-height: 30px;
    width: 32px;
    text-align: center;
  }

  span.active {
    background: #1e90ff;
  }
}

.icon-draw {
  margin-right: 8px;
}

.right-list-box {
  margin-left: 200px;
  min-height: 360px;
  margin-bottom: 30px;

  .icon-delete1 {
    display: none;
  }

  .iconPlayer {
    position: absolute;
    top: calc(50% - 30px);
    left: calc(50% - 20px);
    width: 36px;
    height: 36px;
  }

  .btm {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    max-height: 386px;
    width: 370px;
    padding: 0 20px;

    .drag-move {
      transition: transform 0.5s;
    }

    .el-checkbox {
      display: none;
    }
  }

  .picture-item {
    width: 48%;
    text-align: center;
    height: 122px;
    color: #ffffff;
    cursor: pointer;
    position: relative;
    margin-bottom: 16px;
    border-radius: 4px;
    overflow: hidden;
    border: 1px solid rgba(255, 255, 255, 0);

    .initial {
      position: absolute;
      top: 0;
      right: 0;
      width: 26px;
      height: 26px;
      background: url("../img/initial-point.png") no-repeat;
      background-color: rgba(0, 0, 0, 0.5);
      background-size: 16px;
      border-bottom-left-radius: 4px;
      background-position: 6px 5px;
    }

    .name {
      position: absolute;
      bottom: 0px;
      width: 100%;
      height: 24px;
      line-height: 24px;
      text-align: center;
      color: #ffffff;
      background-color: rgba(34, 34, 34, 0.6);
      font-size: 14px;
      font-weight: 400;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      word-break: break-all;
    }

    .el-checkbox {
      display: none;
      position: absolute;
      top: 4px;
      left: 4px;
    }

    .ibox {
      display: none;
      position: absolute;
      top: calc(50% - 10px);
      left: 50%;
      color: #fff;
      height: 24px;
      width: 24px;
      border-radius: 50%;
      text-align: center;
      margin-top: -12px;
    }

    &:hover .ibox {
      display: inline-block;
    }

    .ibox.edit {
      margin-left: -30px;
      background: #1e90ff;
    }

    .ibox.delete {
      margin-left: 0px;
      background: #fb4e60;
    }

    .icon {
      font-size: 16px;
      line-height: 24px;
      vertical-align: text-bottom;
      display: inline-block;
      width: 24px;
      height: 24px;
    }

    img {
      width: 100%;
      height: 100%;
    }

    &:hover {
      border: 1px solid #fed430;
    }

    &.select {
      border: 1px solid #fed430;
    }
  }

  .thumb-div {
    display: flex;
    width: 336px;
    overflow: hidden;
  }
  .thumb-checkbox{
    margin-top: 20px!important;
    margin-right: 10px!important;
  }
  .thumb-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 3px 12px;
    margin-bottom: 12px;
    border-radius: 4px;
    width: 310px;
    background: rgba(255, 255, 255, 0.15);
    box-sizing: border-box;
    border: 1px solid rgba(255, 255, 255, 0.15);
    height: 70px;
    position: relative;
    z-index: 1666;

    &:hover {
      border: 1px solid #fed430;
      cursor: pointer;
      position: relative;
    }

    > div {
      display: inline-flex;
    }

    .el-checkbox {
      margin-right: 8px;
      line-height: 44px;
    }

    img {
      margin: 0 12px;
      width: 44px;
      height: 44px;
    }

    .rt i {
      margin: 0 4px;
    }

    .record-index {
      line-height: 44px;
    }

    .record-name {
      display: inline-block;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      word-break: break-all;
      width: 140px;
      line-height: 44px;
    }
  }

  &.unlock-list-active {
    .icon-add {
      display: none;
    }

    .icon-delete1 {
      display: inline-block;
    }

    .btm .el-checkbox {
      display: inline-block;
    }
  }
}

.view-layer-selector {
  position: absolute;
  bottom: 6px;
  left: 20px;
}

::v-deep .is-disabled .el-checkbox__inner,
::v-deep .el-checkbox__inner {
  background: transparent;
}
.itemUnLocked{
  pointer-events: none;
}
</style>
